package me.zhengjie.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.service.LocalStorageService;
import me.zhengjie.service.dto.LocalStorageQueryCriteria;
import me.zhengjie.utils.FileUtil;

import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
* @author Zheng Jie
* @date 2019-09-05
*/
@RestController
@RequestMapping("/api/localStorage")
public class LocalStorageController {

	@Autowired
    private LocalStorageService localStorageService;

    @ApiOperation("查询文件")
    @GetMapping
    public ResponseEntity<Object> query(LocalStorageQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @ApiOperation("上传文件")
    @PostMapping
    public ResponseEntity<Object> create(@RequestParam String name, @RequestParam String knowledgeType,  @RequestParam("file") MultipartFile file){
        LocalStorage storage = localStorageService.create(name, knowledgeType, SecurityUtils.getUsername(), file);
        return ResponseEntity.ok(storage);
    }

    /*
    @PostMapping("/pictures")
    public ResponseEntity<Object> upload(@RequestParam MultipartFile file,){
        // 判断文件是否为图片
        String suffix = FileUtil.getExtensionName(file.getOriginalFilename());

        LocalStorage localStorage = localStorageService.create(null, knowledgeType, SecurityUtils.getUsername(), file);
        return new ResponseEntity<>(localStorage, HttpStatus.OK);
    }*/

    @ApiOperation("修改文件")
    @PutMapping
    //@PreAuthorize("@el.check('storage:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody LocalStorage resources){
        localStorageService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @ApiOperation("多选删除")
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        localStorageService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("查询图片")
    @GetMapping(value = "/picture/{uid:.+}")
    public void getPic(@PathVariable String uid, HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline");
        //response.setHeader("Content-Disposition", "attachment;filename=" + uid);
        File file;
        FileInputStream fileIn = null;
        ServletOutputStream out = null;
        try {
            LocalStorage storage = localStorageService.findById(Long.valueOf(uid));
            String filePath = storage.getPath();
            file = new File(filePath);
            fileIn = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] outputByte = new byte[1024];
            int readTmp = 0;
            while ((readTmp = fileIn.read(outputByte)) != -1) {
                out.write(outputByte, 0, readTmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileIn.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}